package com.example.secondassignment;

import java.util.ArrayList;
import com.example.secondassignment.MusicPlayerService.MusicPlayerBinder;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class MP3Player extends ListActivity
{
	
	private MusicPlayerService mpService;
	private Handler popupHandler = new Handler();
	private Activity main_activity;
	
	public static final int NOTIFICATION_ID = 1333;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		
		main_activity = this;
		
		
		final ArrayList<Song> songs = songList();
		setListAdapter(new PlayListAdapter(this, songs));
		getListView().setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long arg3)
			{
				startControls(songs.get(pos));
				//mpService.playSong(songs.get(pos));
				//play(songs.get(pos));
			}
		});
		
		setUpMusicPlayerServiceConnection();
		//startControlsCheck();
	}
	
	@Override
	protected void onDestroy(){
		System.out.println("onDestroy...MP3Player");
		unbindService(mConnection);
		super.onDestroy();
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		//setUpMusicPlayerServiceConnection();
		//mpService.dismissNotification(); // Stop the notification menu
		startControlsCheck();
		System.out.println("onResume...MP3Player");
	}
	
	@Override
	protected void onPause(){
		System.out.println("onPause...MP3Player");
		//unbindService(mConnection);
		super.onPause();
	}
	
	/** 
	 * 
	 * Create and start the music control popup window 
	 * 
	 */
	private void startControls(final Song song){
		
		LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View popupView = layoutInflater.inflate(R.layout.mp3playercontrols, null);
		final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		
		final TextView popupDisplay = (TextView)popupView.findViewById(R.id.songName);
		popupDisplay.setText(song.getName());
		
		ImageButton play = (ImageButton)popupView.findViewById(R.id.palySongButton);
		ImageButton next = (ImageButton)popupView.findViewById(R.id.nextSongButton);
		ImageButton pause = (ImageButton)popupView.findViewById(R.id.pauseSongButton);
		ImageButton previous = (ImageButton)popupView.findViewById(R.id.previousSongButton);
		ImageButton exit = (ImageButton)popupView.findViewById(R.id.dismissControlsButton);
		
		play.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				//showToast("Play");
				mpService.playSong(song);
			}
		});		
		
		next.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				//showToast("Next");
				if(mpService.getCurrentSong() != null){
					mpService.nextSong(mpService.getCurrentSong());
					popupDisplay.setText(mpService.getCurrentSong().getName());
				}
				else{
					mpService.nextSong(song);
				}
			}
		});		
		
		pause.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(mpService.getCurrentSong() != null){
					//showToast("Pause");
					mpService.pauseSong(song);
				}
			}
		});		
		
		previous.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				//showToast("Previous");
				if(mpService.getCurrentSong() != null){
					mpService.previousSong(mpService.getCurrentSong());
					popupDisplay.setText(mpService.getCurrentSong().getName());
				}
				else{
					mpService.previousSong(song);
				}
			}
		});
		exit.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				//showToast("Exit");
				popupWindow.dismiss();
				
			}
		});
		
		/* When you press outside the popupwindow it disapears */		
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		
		/* Set the popupwindow in the middle of the screen */
		popupWindow.showAtLocation(getListView(), Gravity.CENTER, 1, 1);
		
		
		
	}
	
	/** 
	 * 
	 * Start music controls with a delay supposed to be used when we return and a song is already playing 
	 * 
	 */
	private void startControlsCheck(){

		popupHandler.postDelayed(new Runnable() {
			public void run() {
				//System.out.println("mpService "+mpService);
				if( mpService != null){
					//System.out.println("mpService isPlaying() "+mpService.isPlaying());
					if( mpService.isPlaying() ){
						//System.out.println("CurrentSong "+mpService.getCurrentSong());

						startControls(mpService.getCurrentSong()); // Start the popup after the activity has been started
					}
				}
			}
		}, 100 ); // 100 milisec delay
	}
	
	/**
	 * 
	 * Adapter for the playlist
	 * @author Libra
	 *
	 */
	private class PlayListAdapter extends ArrayAdapter<Song>
	{
		public PlayListAdapter(Context context, ArrayList<Song> objects)
		{
			super(context, 0, objects);
		}

		@Override
		public View getView(int position, View row, ViewGroup parent)
		{
			Song data = getItem(position);

			row = getLayoutInflater().inflate(R.layout.layout_row, parent, false);

			TextView name = (TextView) row.findViewById(R.id.label);
			name.setText(String.valueOf(data.getName()));
			row.setTag(data);

			return row;
		}
	}

	/**
	 * Check state of media storage. True if mounted;
	 * @return
	 */
	private boolean isStoreageAvailable()
	{
		return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	}

	/**
	 * Reads song list from media storage.
	 * @return
	 */
	private ArrayList<Song> songList()
	{
		ArrayList<Song> songs = new ArrayList<Song>();

		if(!isStoreageAvailable()) //Check for media storage
		{
			Toast.makeText(this, R.string.nosd, Toast.LENGTH_SHORT).show();
			return songs;
		}
		Toast.makeText(this, "MediaStore is mounted", Toast.LENGTH_SHORT).show();
		
		Cursor music = getContentResolver().query( //using content resolver to read music from media storage
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
				new String[]{
						MediaStore.Audio.Media._ID,
						MediaStore.Audio.Media.ARTIST,
						MediaStore.Audio.Media.ALBUM,
						MediaStore.Audio.Media.DISPLAY_NAME,
						MediaStore.Audio.Media.DATA},
				MediaStore.Audio.Media.IS_MUSIC + " > 0 ",
				null, null
		);
		System.out.println("music: "+music);
		

		if(music.getCount() > 0)
		{
			//Toast.makeText(this, "Seems like we found some music", Toast.LENGTH_SHORT).show();
			
			music.moveToFirst();
			Song prev = null;
			do
			{
				Song song = new Song(music.getString(0), music.getString(1), music.getString(2), music.getString(3), music.getString(4));
				System.out.println(song.toString());
				if(prev != null){ //here prev song linked to current one. To simple play them in list
					prev.setNext(song);
					song.setPrevious(prev);
				}

				prev = song;
				songs.add(song);
			}
			while(music.moveToNext());
			
			prev.setNext(songs.get(0)); //play in cycle;
		}else{
			Toast.makeText(this, "Music getCount < 0", Toast.LENGTH_SHORT).show();
		}
		music.close();

		return songs;
	}
	
	/**
	 * 
	 *  Defines callbacks for service binding, passed to bindService() 
	 *  
	 */
    private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to MusicPlayerBinder, cast the IBinder and get MusicPlayerBinder instance
			MusicPlayerBinder binder = (MusicPlayerBinder) service;
			mpService = binder.getService();
			
			Intent music = new Intent();
			music.setClass(main_activity,MusicPlayerService.class);
			startService(music);
		}
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			
		}
    };
	
	private void setUpMusicPlayerServiceConnection(){
		Intent musicPlayerServiceIntent = new Intent(MP3Player.this,MusicPlayerService.class);
		bindService(musicPlayerServiceIntent, mConnection, MP3Player.BIND_AUTO_CREATE);
	}
	
	/**
	 * @author Libra
	 * 
	 * Shut down the music player and notification and service and everything !!
	 * 
	 */
	private void shutDownMP3Player(){
		try{
			mpService.stopService();
			finish();
		}
		catch(Exception e){
			showToast("Error: "+e+"- Please stop the music befor shuting down");
		}
	}

    /*
     *  Adding option menus 
     */
	private static final int SHUT_DOWN = 0;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.action_menu_mpplayer, menu);
		
		return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) { 	
    	switch (item.getItemId()) {
        case R.id.shutdown_MPPlayer:  	
        	shutDownMP3Player();
        	return true;
        } 
    	return false;
    }
	
	/* Diagnostics while developing */
    
    private void showToast(String msg) {
    	Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
	
}
